package com.cxb.aes;


import cn.hutool.core.date.DateUtil;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/aes")
@Slf4j
public class AesController {

    @GetMapping("test")
    public String test(){
        return "!2";
    }

    private static final String START = "start";
    private static final String END = "end";

    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String originalString = "The text to be encrypted";
        String secretKey = "1234567812345678";

        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");

        // Encryption
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(originalString.getBytes(StandardCharsets.UTF_8));

        System.out.println("AES encrypted string: " + new String(encryptedBytes, StandardCharsets.UTF_8));

        // Decryption
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        System.out.println("AES decrypted string: " + new String(decryptedBytes, StandardCharsets.UTF_8));
    }

    private Map<String, Date> generatedDate(String start, String end) {
        // 创建一个用于存储开始和结束时间的Map
        Map<String, Date> dateMap = Maps.newHashMap();
        Calendar calendar = Calendar.getInstance();
        if (StrUtil.isBlank(start) || StrUtil.isBlank(end)) {
            // start
            calendar.add(Calendar.MONTH, -1); // 上个月
            calendar.set(Calendar.DAY_OF_MONTH, 8); // 8号
            start = String.valueOf(calendar.getTime());
            // end
            calendar.add(Calendar.MONTH, 0); // 本月
            calendar.set(Calendar.DAY_OF_MONTH, 9); // 9号
            end = calendar.getTime().toString();
        }
        Date startDate = DateUtil.parse(start);
        Date endDate = DateUtil.parse(end);
        dateMap.put(START, startDate);
        dateMap.put(END, endDate);
        return dateMap;
    }
}
